import { computed, reactive } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import i18n from '@/i18n';
import { useProjectSettingStore } from '@/store/modules/projectSetting';
import { getDictData } from '@/api/common/index';
// import config from '@/config';
import { useMessage } from 'naive-ui';
import { cloneDeep, isEqual } from 'lodash-es';

import { useAsyncRouteStoreWidthOut } from '@/store/modules/asyncRoute';

import { http } from '@/utils/http/axios';
import { storage } from '@render/utils/Storage';

// const { VUE_APP_BASE_URL } = config;

const VUE_APP_BASE_URL = `http://${storage.get('host')}:3000`;

const urlPrefix = VUE_APP_BASE_URL || '';

const asyncRouteStore = useAsyncRouteStoreWidthOut();

// if (process.env.NODE_ENV === 'development') {
//   if (VUE_APP_API_URL.includes('dfdsdev')) {
//     urlPrefix = '/devApi';
//   } else if (VUE_APP_API_URL.includes('dfdstest')) {
//     urlPrefix = '/testApi';
//   } else if (VUE_APP_API_URL.includes('dfdsuat')) {
//     urlPrefix = '/uatApi';
//   }
// }

export const useMixins: any = () => {
  const message = useMessage();

  const route = useRoute();
  const router = useRouter();

  const settingStore = useProjectSettingStore();

  const { t, getLocaleMessage, mergeLocaleMessage } = i18n.global;

  const state: any = reactive({
    routerPage: '',
    routerType: '',
    routerTitle: '',
    routeAuthCode: '',
    langPage: '',
    backPath: '',
    detailListName: '',
  });

  const routePath = route.path;

  if (route) {
    const val = route.path;

    const routeName: any = route.name || '';

    if (val.indexOf('/add') !== -1) {
      state.routerType = 'add';

      state.backPath = val.split('/add')[0];

      state.detailListName = routeName.split('Add')[0];
    } else if (val.indexOf('/edit/') !== -1) {
      state.routerType = 'edit';

      state.backPath = val.split('/edit/')[0];

      state.detailListName = routeName.split('Edit')[0];
    } else if (val.indexOf('/check/') !== -1) {
      state.routerType = 'check';

      state.backPath = val.split('/check/')[0];

      state.detailListName = routeName.split('Check')[0];
    } else if (val.indexOf('/copy/') !== -1) {
      state.routerType = 'copy';

      state.backPath = val.split('/copy/')[0];

      state.detailListName = routeName.split('Copy')[0];
    } else if (val.indexOf('/print/') !== -1) {
      state.routerType = 'print';

      state.backPath = val.split('/print/')[0];

      state.detailListName = routeName.split('Print')[0];
    }
  }

  if (route && route.name) {
    let name: any = route.name || '';

    name = name.replace(name.charAt(0), name.substring(0, 1).toLowerCase());

    state.routerPage = name;
  }

  if (route && route.meta && route.meta.authCode) {
    state.routeAuthCode = route.meta.authCode || '';
  }

  // 按需加载语言包
  const loadLangFn = (lang, routerName = state.routerPage) => {
    if (!getLocaleMessage('zh')[routerName]) {
      mergeLocaleMessage('en', lang.en);

      mergeLocaleMessage('zh', lang.zh);
    }
  };
  const getPageLangValueFn = (name, langPage) => {
    if (!state.routerPage) {
      return '';
    }

    return t(`${langPage || state.routerPage}.${name}`);
  };

  const getTableLabelFn = (item, langPage) => {
    if (item.common) {
      return t(`common.table.${item.label}`);
    }

    return item.label ? t(`${langPage || state.routerPage}.table.${item.label}`) : '';
  };

  const getFormLabelFn = (item, langPage) => {
    if (item.common) {
      return t(`common.form.${item.label}`);
    }

    return item.label ? t(`${langPage || state.routerPage}.form.${item.label}`) : '';
  };

  // language
  const language = computed(() => {
    return settingStore.language;
  });

  // 表格数据前端分页
  const handleTablePageFn = (tableList, queryParams) => {
    const { pageSize, pageNum } = queryParams;
    // console.log(pageSize, pageNum);

    return tableList
      ? tableList.length <= pageSize
        ? tableList
        : tableList.slice((pageNum - 1) * pageSize, pageSize * pageNum)
      : [];
  };

  // 英文名称首字母小写
  const toLowerCaseFn = (val, noNeedKey) => {
    return language.value === 'zh'
      ? val
      : noNeedKey
      ? val.slice(0, val.indexOf(noNeedKey)).toLowerCase() + val.slice(val.indexOf(noNeedKey))
      : val.toLowerCase();
  };

  /**
   * 空数据替换为"-"
   */
  const replaceNullFn = (data) => {
    if ([null, undefined, ''].includes(data)) {
      return '-';
    }
    return data;
  };

  //字典表
  const getDictDataListFn = async (
    dictTypeCode = '',
    type = 'crm',
    labelKey = 'dictionaryName',
    valueKey = 'dictionaryCode'
  ) => {
    const list: any = [];
    if (dictTypeCode && labelKey && valueKey) {
      try {
        const res = await getDictData(dictTypeCode, type);

        const { data = [] } = res;

        if (data && data.length) {
          for (const item of data) {
            list.push({ label: item[labelKey], value: item[valueKey],extend1:item['extend1'],extend2:item['extend2'] });
          }
        }
      } catch (e) {
        console.log(e);
      }
    }

    return list;
  };

  //返回查询页是否清除keepAlive缓存
  const clearKeepAliveFn = (routeName) => {
    const keepAliveComponents = asyncRouteStore.keepAliveComponents;
    const index = asyncRouteStore.keepAliveComponents.findIndex((name) => name == routeName);
    if (index != -1) {
      keepAliveComponents.splice(index, 1);
    }
    asyncRouteStore.setKeepAliveComponents(keepAliveComponents);
  };

  // 通用导出方法
  const downloadFn = (fileName) => {
    window.location.href =
      urlPrefix + '/common/download?fileName=' + encodeURI(fileName) + '&delete=' + true;
  };

  // 通用下载模板方法
  const downloadFileFn = (fileName) => {
    window.location.href = urlPrefix + '/common/download/file/' + encodeURI(fileName);
  };

  const getNowDateFn = () => {
    const time: any = new Date();
    const Y = time.getFullYear();
    const M = time.getMonth() + 1;
    const D = time.getDate();
    const h = time.getHours();
    const m = time.getMinutes();
    const s = time.getSeconds();
    const currentDate = `${Y}${addZeroFn(M)}${addZeroFn(D)}${addZeroFn(h)}${addZeroFn(
      m
    )}${addZeroFn(s)}`;
    return currentDate;
  };

  // 判断数字小于10前面补 0
  const addZeroFn = (n) => {
    if ((n || n == 0) && n < 10) {
      return '0' + n;
    }
    return n;
  };
  // 删除
  const handleDeleteFn = (id: any, api: Fn, reload?: Fn, errorFn?: Fn) => {
    const message = window['$message'];
    const d = window['$dialog'].warning({
      title: t('common.tipMsg.warning'),
      content: t('common.tipMsg.deleteSelectedMsg'),
      positiveText: t('common.tipMsg.sure'),
      negativeText: t('common.tipMsg.cancel'),
      onPositiveClick: async () => {
        try {
          d.loading = true;
          const { message: msg = '' } = await api(id);
          message.success(msg || t('common.tipMsg.delSuccess'));
          reload && reload();
        } catch (e) {
          console.log(e);
          errorFn && errorFn(e);
          d.loading = false;
        }
      },
      onNegativeClick: () => {},
      onAfterLeave: () => {
        d.loading = false;
      },
    });
  };
  /**
   *
   * @param option  提示配置，通常只需重写content即可
   * @param sure    确认方法
   * @param cancel  取消方法
   * @param otherFn 其他方法
   */
  const dialogWarningFn = (option: Recordable, sure: Fn, cancel?: Fn, otherFn?: Object) => {
    const d = window['$dialog'].warning({
      title: t('common.tipMsg.warning'),
      content: t('common.tipMsg.deleteSelectedMsg'),
      positiveText: t('common.tipMsg.sure'),
      negativeText: t('common.tipMsg.cancel'),
      ...option,
      onPositiveClick: async () => {
        d.loading = true;
        sure && sure();
      },
      onNegativeClick: () => {
        cancel && cancel();
      },
      onAfterLeave: () => {
        d.loading = false;
      },
      ...otherFn,
    });
  };
  //公用跳转
  const routerGoFn = (type = 'add', id = '', path = '') => {
    path = path || routePath;
    path = `${path}/${type}`;
    if (id) path = `${path}/${id}`;
    router.push({ path });
  };

  const downloadNameFn = (fileName, fileType?) => {
    const time = new Date();
    const Y = time.getFullYear();
    const M = time.getMonth() + 1;
    const D = time.getDate();
    const h = time.getHours();
    const m = time.getMinutes();
    const s = time.getSeconds();
    const currentDate = `${Y}${addZeroFn(M)}${addZeroFn(D)}${addZeroFn(h)}${addZeroFn(
      m
    )}${addZeroFn(s)}`;
    const name = fileType
      ? language.value === 'zh'
        ? `${fileName}${currentDate}`
        : `export${currentDate}`
      : language.value === 'zh'
      ? `${fileName}${currentDate}.xlsx`
      : `export${currentDate}.xlsx`;
    return name;
  };

  //导出公共方法
  const handleExportFn = (
    data: any = {},
    ids: any = [],
    api: Fn = () => {},
    key = 'id',
    exportName = downloadNameFn(t(`route.${state.routerPage}`))
  ) => {
    if (data && data.entity) {
      const recordIds = ids && ids.length > 0 ? ids : undefined;

      const confirmText = recordIds
        ? t('common.tipMsg.exportSelected')
        : t('common.tipMsg.exportAll');

      // const message = window['$message'];

      const d = window['$dialog'].warning({
        title: t('common.tipMsg.info'),
        content: confirmText,
        positiveText: t('common.tipMsg.sure'),
        negativeText: t('common.tipMsg.cancel'),
        onPositiveClick: async () => {
          try {
            d.loading = true;

            data.entity[key] = ids || [];

            await api(data, exportName);
          } catch (e) {
            console.log(e);

            d.loading = false;
          }
        },
        onNegativeClick: () => {},
        onAfterLeave: () => {
          d.loading = false;
        },
      });
    }
  };

  const handleTree = (data, id, parentId, children) => {
    const config = {
      id: id || 'id',
      parentId: parentId || 'parentId',
      childrenList: children || 'children',
    };

    const childrenListMap = {};
    const nodeIds = {};
    const tree: any = [];

    for (const d of data) {
      const parentId = d[config.parentId];
      if (childrenListMap[parentId] == null) {
        childrenListMap[parentId] = [];
      }
      nodeIds[d[config.id]] = d;
      childrenListMap[parentId].push(d);
    }

    for (const d of data) {
      const parentId = d[config.parentId];
      if (nodeIds[parentId] == null) {
        tree.push(d);
      }
    }

    for (const t of tree) {
      adaptToChildrenList(t);
    }

    function adaptToChildrenList(o) {
      if (childrenListMap[o[config.id]] !== null) {
        o[config.childrenList] = childrenListMap[o[config.id]];
      }
      if (o[config.childrenList]) {
        for (const c of o[config.childrenList]) {
          adaptToChildrenList(c);
        }
      }
    }
    return tree;
  };

  // 表单返回方法
  /**
   *
   * @param {string} id               编辑/新增页面id(或唯一标识)
   * @param {object} routeObj         页面路由对象
   * @param {object} form             页面数据(返回时的当前数据)
   * @param {object} oldform          页面数据(初始)
   * @param {string} queryUrl         页面路径
   */

  const toBackFn = (id, _routeObj, form, oldform, queryUrl) => {
    if (id || !isEqual(oldform, form)) {
      const dialog = window['$dialog'];

      dialog.warning({
        class: 'dialogBtn',
        title: t('common.tipMsg.info'),
        content: t('common.tipMsg.backConfirm'),
        positiveText: t('common.tipMsg.sure'),
        negativeText: t('common.tipMsg.cancel'),
        positiveButtonProps: {
          color: '#393e58',
          // type: 'info',
        },
        onPositiveClick: () => {
          if (queryUrl) {
            router.push(queryUrl);
          } else {
            router.go(-1);
          }
        },
        onNegativeClick: () => {
          // message.error('不确定');
        },
      });
    } else {
      if (queryUrl) {
        router.push(queryUrl);
      } else {
        router.go(-1);
      }
    }
  };

  // 获取临时下载链接
  const downLoadFile = (obj) => {
    const { fileUrl = '', fileName, getDownloadUrl = '/oss/file/temp/url', type } = obj;
    // const urlArr = fileUrl.split('||');
    let params: any = {
      url: fileUrl,
    };

    let method = 'post';

    if (type) {
      params = {
        type,
      };

      method = 'get';
    }

    return http
      .request({
        url: getDownloadUrl,
        method,
        params,
      })
      .then(async (res) => {
        let url = res?.row?.temUrl;

        if (url) {
          url = url.replace('http:', window.location.protocol);

          url = url.replace('https:', window.location.protocol);

          http
            .request({
              url,
              method: 'get',
              dataType: 'jsonp',
              responseType: 'blob',
              fileName,
              headers: {
                isToken: false,
              },
            })
            .then((fileRes) => {
              console.log(fileRes);

              // console.log('fileRes', fileRes);
            });
        }

        // console.log('url', url);
        // window.open(url);
        // const { fileName = '' } = obj;
        // // download(url, fileName, 'image/png');
        // const eLink = document.createElement('a');
        // try {
        //   eLink.download = fileName;
        //   eLink.style.display = 'none';
        //   eLink.target = '_Blank';
        //   eLink.href = url;
        //   document.body.appendChild(eLink);
        //   eLink.click();
        // } finally {
        //   document.body.removeChild(eLink);
        // }
      })
      .catch((err) => {
        console.log('err', err);
      });
    // 下载不调后端接口，前端处理
    /*
    .then((tempRes) => {

      return request({
        url: `/oss/file/download?fileName=${tempRes?.row?.temUrl}`,
        method: 'get',
        responseType: 'blob',
        fileName
      });

    });
      */
  };

  return {
    ...unref(state),
    // routerType: state.routerType,
    // backPath: state.backPath,
    language: ref(language),
    loadLangFn,
    getPageLangValueFn,
    getTableLabelFn,
    getFormLabelFn,
    handleTablePageFn,
    toLowerCaseFn,
    replaceNullFn,
    getDictDataListFn,
    downloadFn,
    downloadFileFn,
    getNowDateFn,
    handleDeleteFn,
    handleExportFn,
    downloadNameFn,
    routerGoFn,
    dialogWarningFn,
    message,
    t,
    cloneDeep,
    handleTree,
    toBackFn,
    router,
    clearKeepAliveFn,
    downLoadFile,
  };
};
